<!--
 * @Description:  附近门店
 * @Author: Kerwin
 * @Date: 2023-11-19 17:53:57
 * @LastEditTime: 2025-08-20 16:39:42
 * @LastEditors:  Please set LastEditors
-->
<template>
  <view class="c_container">
    <page-skeleton :loading="loadingSkeleton" :type="2"></page-skeleton>
    <view class="shop" v-for="(shop, index) in shopList.list" :key="shop.id">
      <view class="contentBox" @click="toShopDetail(shop)">
        <view>
          <u-image
            width="120rpx"
            height="120rpx"
            :src="getImgFullPath(shop.avatar)"
          ></u-image
        ></view>
        <view class="content">
          <view class="name">
            {{ shop.name
            }}<u-tag
              v-if="!shop.isOpen"
              text="未营业"
              style="margin-left: 20rpx"
              mode="dark"
              size="mini"
              type="error"
            />
          </view>
          <view class="addr">
            <view class="msg">
              <u-icon name="map-fill" class="icon"></u-icon>
              <text>{{ shop.addr }}</text>
            </view>
            <text class="distance">距您{{ shop.distance }}</text>
          </view>
          <view v-if="index == 0" class="tagActive"> 离您最近 </view>
        </view>
      </view>
    </view>
    <u-back-top :scroll-top="scrollTop"></u-back-top>
    <u-loadmore :status="status" :load-text="loadText" />
  </view>
  <u-empty v-if="isEmpty" text="附近没有门店入驻" mode="list"></u-empty>
</template>

<script setup lang="ts">
import { reactive, ref, onMounted, watch, watchEffect } from 'vue'
import { onReachBottom, onPageScroll, onShow, onLoad } from '@dcloudio/uni-app'
//api
import { productApi, baseApi, userApi } from '@/api'
//工具
import {
  getLocation,
  getDistance,
  handleMapLocation,
  checkLoginState,
  getWZLocation,
  getImgFullPath
} from '@/utils'
import * as WzLocation from '@/utils/wz_sdk_uniapp.js'
console.log(WzLocation, '初始化接入维智..')
import { storeToRefs } from 'pinia'
import { useConfigStore, useUserStore, useShopInfoStore } from '@/store'
import pageSkeleton from '@/components/hy-page-skeleton/index.vue'
import { mode } from 'crypto-js'

//interface
interface Address {
  cityShortName?: string
  cityName?: string
  districtName?: string
  provinceName?: string
  provinceId?: number
  cityId?: number
  districtId?: number
}

//props
const props = defineProps({
  integralsRuleId: {
    type: Number,
    default: null
  },
  isApp: {
    type: Boolean,
    default: false
  },
  address: {
    type: Object,
    default: {}
  },
  brandId: {
    type: Number,
    default: {}
  },
  searchShopName: {
    type: String,
    default: ''
  },
  refresh: {
    type: Boolean,
    default: false
  }
})

const getAdr = ref<any>({})
const brandId = ref()

//初始化数据
const loadingSkeleton = ref(false)
const userStore = useUserStore()
const { userInfo } = storeToRefs(userStore)
const shopInfoStore = useShopInfoStore()
const configStore = useConfigStore()
const status = ref('loading')
const currentLocation = ref()
const distance = ref(null)
const addressObj = ref<any>({})
// 门店列表
const shopList = reactive<any>({
  pageIndex: 1,
  pageSize: 10,
  list: []
})
const scrollTop = ref(0)
let isPageLoaded = false
let isEmpty = false
const loadText = {
  loadmore: '正在加载更多',
  loading: '正在加载首次定位，请耐心等待',
  nomore: '实在没有了'
}
const Mode = ref(4)
//app用户信息
const APPUSE = (fun: any) => {
  console.log('判断app免登录配置')
  if (props.isApp) {
    console.log('进入APPUSE1直接使用')
    // #ifdef H5
    // @ts-ignore
    window.JSBridge.registerEvent('HYUserEvent', async () => {
      fun
    })
    // #endif
    // #ifdef H5
    // @ts-ignore
    window.JSBridge.HYUserEvent()
    console.log('调取成功？')

    // #endif
  } else {
    console.log('进入h5直接使用')
    fun
  }
}

//获取附近餐厅列表
const getShopList = async (str?: any) => {
  console.log('知道从哪儿来=》', str)

  if (status.value === 'nomore') return
  status.value = 'loading'
  let obj = {
    pageIndex: shopList.pageIndex,
    pageSize: shopList.pageSize,
    shopBrandId: Number(brandId.value),
    distance: distance.value,
    keywords: props.searchShopName,
    shopMode: Number(Mode.value)
  }
  console.log('列表', getAdr.value)

  if (getAdr.value) obj = { ...obj, ...getAdr.value }
  const { data, code } = await productApi.getRestaurantList(obj)
  if (code !== 200) return (isEmpty = true)
  const { records, current, pages } = data
  let list = records.map((shop: any) => {
    const { provinceName, cityName, address } = shop
    shop.addr = provinceName + cityName + address
    if (currentLocation.value) {
      const { latitude, longitude } = currentLocation.value
      getDistance(latitude, longitude, shop.latitude, shop.longitude).then(
        (res: any) => {
          const { distance_str } = res
          shop.distance = distance_str
        }
      )
    } else {
      shop.distance = formatDistance(shop.distance)
    }

    return shop
  })

  shopList.list.push(...list)
  const index = shopList.list.findIndex((item) => item.id === 3)
  const index2 = shopList.list.findIndex((item) => item.id === 11)
  const index3 = shopList.list.findIndex((item) => item.id === 21)
  if (index > 0 && configStore.hideData) {
    shopList.list.splice(index, 1)
    shopList.list.splice(index2, 1)
    shopList.list.splice(index3, 1)
  }
  if (current < pages) {
    shopList.pageIndex += 1
  } else {
    status.value = 'nomore'
  }
}

// 监听 props 变化并触发门店列表刷新
const refreshShopList = async () => {
  // 重置分页信息
  shopList.pageIndex = 1
  shopList.list = []
  status.value = 'loading'
  loadText.loading = '正在搜索，请耐心等待'
  APPUSE(getShopList(4))
}

// 调用list初始化状态
let initStatus = {
  isComponentMounted: false,
  isDataLoaded: false,
  isReadyToListen: false
}

onMounted(() => {
  initStatus.isComponentMounted = true
})
// 统一监听 props 的变化
watch(
  () => props.searchShopName,
  (newVal, oldVal) => {
    if (initStatus.isReadyToListen && newVal !== oldVal) {
      refreshShopList()
    }
  }
)
watch(
  () => props.address,
  (newVal, oldVal) => {
    console.log('获取搜索指令地址:', newVal, oldVal)
    if (newVal) {
      getAdr.value = newVal
      // 当地址变化时，触发数据重新加载
      refreshShopList()
    }
  },
  { deep: true }
)

//返回顶部
onPageScroll((e) => {
  scrollTop.value = e.scrollTop
})

// 获取当前模式
function toShopDetail(shop: any) {
  let shopInfo = {
    id: shop.restaurantId,
    adress: shop.addr,
    distance: shop.distance,
    name: shop.name
  }
  shopInfoStore.setShopInfo({ ...shop })
  console.log(shop.shopBrandId, '88888888', Mode.value)

  uni.navigateTo({
    url: `/pages/bigLife/orderShop?brandId=${shop.shopBrandId}&shopId=${shopInfo.id}&address=${shopInfo.adress}&distance=${shop.distance}&name=${shop.name}&shopMode=${Mode.value}`
  })
}

onReachBottom(() => {
  if (!isPageLoaded) return
  loadText.loading = '正在加载更多'
  APPUSE(getShopList(5))
})
//公里转换
function formatDistance(km: number): string {
  if (km >= 1) {
    return `${km.toFixed(1)}km`
  } else {
    const meters = km * 1000
    return `${meters.toFixed(1)}m`
  }
}

onLoad(async (option: any) => {
  console.log(option, 55555)
  loadingSkeleton.value = true
  brandId.value = option.brandId
  Mode.value = option?.mode || 4
  await getShopList(1)
  initStatus.isDataLoaded = true
  setTimeout(() => {
    initStatus.isReadyToListen = true
  }, 0)
  setTimeout(() => {
    loadingSkeleton.value = false
  }, 100)
  isPageLoaded = true
})
</script>

<style lang="scss" scoped>
@import '@/styles/helper.scss';

.c_container {
  // display: flex;
  justify-content: flex-start;
  flex-wrap: wrap;
  gap: 20rpx;

  .shop {
    // border-radius: $section-raduis;
    // background: $uni-bg-color-white;
    margin-bottom: $uni-spacing-col-lg;
    padding: $uni-spacing-row-lg;
    box-shadow: 0rpx 8rpx 16rpx 0rpx rgba(0, 0, 0, 0.07);
    background-color: rgba(255, 255, 255, 1);
    border-radius: 20rpx;

    .contentBox {
      display: flex;
      align-items: center;

      .imgCover {
        position: relative;
        width: 160rpx;
        flex-shrink: 0;
        margin-right: 20rpx;

        .img {
          width: 100%;
          // height: 200rpx;
          border-radius: $section-raduis;
        }
      }

      .content {
        position: relative;
        flex: 1;
        text-align: left;
        margin-left: 20rpx;

        .tagActive {
          position: absolute;
          right: -30rpx;
          top: -30rpx;
          padding: 10rpx;
          //width: 100rpx;
          color: #feb48c;
          font-size: 20rpx;
          background-color: #fef1ec;
        }

        .name {
          width: 100%;
          display: flex;
          flex-wrap: nowrap;
          font-size: 32rpx;
          display: inline-block;
        }

        .remark {
          @include ellipsis;
          color: $uni-text-color-light;
          font-size: 20rpx;
          margin-top: 10rpx;
        }

        .addr {
          display: flex;
          justify-content: space-between;
          align-items: center;
          font-size: 20rpx;
          color: $uni-text-color-light;
          gap: 10rpx;
          margin-top: 30rpx;

          .msg {
            display: flex;
            justify-content: flex-start;
            align-items: center;

            .icon {
              font-size: 26rpx;
              color: #333;
              margin-right: 5rpx;
            }
          }

          .distance {
            flex-shrink: 0;
            margin-left: 10rpx;
          }
        }

        .vip {
          position: absolute;
          right: 0;
          top: 0;
          border: 1px solid $uni-text-color-red;
          color: $uni-text-color-red;
          font-size: 18rpx;
          padding: 5rpx;
          border-radius: 10rpx;
        }
      }
    }

    .couponBox {
      display: flex;
      overflow-y: scroll;
      align-items: flex-start;

      .coupon_voucher {
        border-radius: 6px;
        box-shadow: 0 0 6px 0 rgba(0, 0, 0, 0.1);
        color: $uni-text-color-orange;
        margin: 20rpx 20rpx 20rpx 6rpx;
        padding: 7px 10px 10px;
        position: relative;
        width: 250rpx;
        flex-shrink: 0;

        &_main {
          // min-height: 100rpx;
          .price {
            .unit {
              font-size: 20rpx;
            }

            .num {
              font-size: 40rpx;
              font-weight: bold;
            }
          }

          .name {
            font-size: 22rpx;
          }
        }

        &_foot {
          border-top: 1px dashed $uni-border-color-orange;
          margin-top: 10px;
          padding-top: 8px;
          position: relative;
          display: flex;
          justify-content: center;

          &::before,
          &::after {
            background-color: #fff;
            border-color: transparent transparent rgba(232, 232, 237, 0.7)
              rgba(232, 232, 237, 0.7);
            border-radius: 50%;
            border-style: solid;
            border-width: 1px;
            content: '';
            height: 7px;
            position: absolute;
            top: -4px;
            width: 7px;
          }

          &::before {
            left: -15px;
            transform: rotate(-135deg);
          }

          &::after {
            right: -15px;
            transform: rotate(35deg);
          }

          :deep(.btn) {
            flex: 1;

            button {
              padding: 8rpx 0;
              font-size: 20rpx;
              height: 40rpx;
              width: 100%;
            }
          }
        }
      }
    }

    .actionBox {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-top: 20rpx;

      .rule {
        color: $uni-text-color-light;
        font-size: 20rpx;
      }

      .actions {
        display: flex;
        justify-content: center;
        gap: 18rpx;

        :deep(.u-btn--primary) {
          background: $bg-primary;
        }

        .hy-icon-dianhua {
          margin-right: 5rpx;
          font-size: 26rpx;
        }
      }
    }
  }
}

:deep(.u-image__image) {
  border-radius: 10rpx !important;
}
</style>
